# Compound Components

<EpicVideo url="https://www.epicreact.dev/workshops/advanced-react-patterns/intro-to-compound-components" />

<callout-success>
	**One liner:** The Compound Components Pattern enables you to provide a set of
	components that implicitly share state for a simple yet powerful declarative
	API for reusable components.
</callout-success>

Compound components are components that work together to form a complete UI. The
classic example of this is `<select>` and `<option>` in HTML:

```html
<select>
	<option value="1">Option 1</option>
	<option value="2">Option 2</option>
</select>
```

The `<select>` is the element responsible for managing the state of the UI, and
the `<option>` elements are essentially more configuration for how the select
should operate (specifically, which options are available and their values).

Let's imagine that we were going to implement this native control manually. A
naive implementation would look something like this:

```tsx
<CustomSelect
	options={[
		{ value: '1', display: 'Option 1' },
		{ value: '2', display: 'Option 2' },
	]}
/>
```

This works fine, but it's less extensible/flexible than a compound components
API. For example. What if I want to supply additional attributes on the
`<option>` that's rendered, or I want the `display` to change based on whether
it's selected? We can easily add API surface area to support these use cases,
but that's just more for us to code and more for users to learn. That's where
compound components come in really handy!

For the rest of the exercises in this workshop, we'll be working with a simple
`<Toggle />` component.

Every reusable component starts out as a simple implementation for a specific
use case. It's advisable to not overcomplicate your components and try to solve
every conceivable problem that you don't yet have (and likely will never have).
But as changes come (and they almost always do), then you'll want the
implementation of your component to be flexible and changeable. One of the most
important abilities of a software developer is optimizing for change. Learning
how to do that is the point of much of this workshop.

This is why we're starting with a super simple `<Toggle />` component. You'll be
surprised how feature-rich we can make a simple toggle component. Keeping it
simple allows us to focus in on making it reusable without getting distracted by
the complexities of the feature implementation (like we would if we were
building a date picker or something 😅).

Shout-out to [Ryan Florence](https://twitter.com/ryanflorence) for creating this
pattern.

**Real World Projects that use this pattern:**

- [`@radix-ui/react-tabs`](https://www.radix-ui.com/primitives/docs/components/tabs)
- [`@radix-ui/react-accordion`](https://www.radix-ui.com/primitives/docs/components/accordion)
- Actually most of [Radix UI](https://www.radix-ui.com/primitives) implements
  this pattern
